const { constants } = require("buffer");

module.exports = (app) => {
  const express = require("express");
  const router = express.Router({
    mergeParams: true,
  });
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");
  const ok = require("assert");
  const AdminUser = require("../../models/AdminUser");
  const Category = require("../../models/Category");
  const Article = require("../../models/Article");

  /**
   * 校验登录中间件
   */
  const auth = require("../../middleware/auth");

  /**
   * 验证是否登录
   */
  router.get("/auth", async (req, res, next) => {
    const token = String(req.headers.token || "");
    assert(token, 401, "请先登录");

    const { id } = jwt.verify(token, req.app.get("secret"));
    assert(id, 401, "请先登录");

    req.user = await AdminUser.findById(id);
    assert(req.user, 401, "请先登录");
    // console.log(req.user)
    res.send({
      success: true,
      data: {
        userName: req.user.userName,
        userId: req.user._id,
      },
    });
  });

  /* 类别接口 */
  router.post("/newCategory", auth(), async (req, res, next) => {
    const model = await Category.create(req.body);
    res.send({
      success: true,
      data: model,
    });
  });
  router.get("/Categories", auth(), async (req, res, next) => {
    const items = await Category.find().limit(10);
    res.send({ success: true, data: items });
  });
  router.put("/editCategory", auth(), async (req, res, next) => {
    const model = await Category.findByIdAndUpdate(req.body.id, req.body);
    res.send({ success: true, data: model });
  });
  router.delete("/removeCategory/:id", auth(), async (req, res, next) => {
    await Category.findByIdAndDelete(req.params.id, req.body);
    res.send({
      success: true,
      data: "",
    });
  });

  /* 文章接口 */
  router.post("/article/newArticle", auth(), async (req, res, next) => {
    const model = await Article.create(req.body);
    // console.log(req.body);
    res.send({ success: true, data: model });
  });
  router.get("/article/getArticles", auth(), async (req, res, next) => {
    const items = await Article.find().populate("categoryNames").limit(10);
    res.send({ success: true, data: items });
  });
  router.put("/article/editArticle", auth(), async (req, res, next) => {
    const model = await Article.findByIdAndUpdate(req.body._id, req.body);
    res.send({
      success: true,
      data: model,
    });
  });
  router.delete(
    "/article/removeArticle/:id",
    auth(),
    async (req, res, next) => {
      await Article.findByIdAndDelete(req.params.id, req.body);
      res.send({
        success: true,
        data: "",
      });
    }
  );

  /** 管理员接口 */
  router.post("/adminUser/newAdminUser", auth(), async (req, res, next) => {
    const model = await AdminUser.create(req.body);
    res.send({
      success: true,
      data: model,
    });
  });
  router.get("/adminUser/AdminUsersList", auth(), async (req, res, next) => {
    const items = await AdminUser.find().limit(10);
    res.send({ success: true, data: items });
  });
  router.put("/adminUser/editAdminUser", auth(), async (req, res, next) => {
    const model = await AdminUser.findByIdAndUpdate(req.body.id, req.body);
    console.log(req.body);
    res.send({
      success: true,
      data: model,
    });
  });
  router.delete(
    "/adminUser/removeAdminUser/:id",
    auth(),
    async (req, res, next) => {
      await AdminUser.findByIdAndDelete(req.params.id, req.body);
      res.send({
        success: true,
        data: "",
      });
    }
  );

  /**
   * 图片上传
   */
  const multer = require("multer");
  const upload = multer({ dest: __dirname + "/../../uploads" });
  app.post(
    "/admin/api/upload",
    auth(),
    upload.single("file"),
    async (req, res, next) => {
      const file = req.file;
      console.log(file);
      file.url = `http://localhost:3000/uploads/${file.filename}`;
      res.send({ data: file, success: true });
    }
  );

  /**
   * 登录部分
   */
  app.post("/admin/api/login", async (req, res, next) => {
    // console.log(req.body);
    const { userName, password } = req.body;
    // 1.根据用户名找用户
    const user = await AdminUser.findOne({ userName: userName }).select(
      "+password"
    );
    assert(user, 422, "用户不存在");

    // 2.检验密码
    const isValid = require("bcrypt").compareSync(password, user.password);
    assert(isValid, 422, "密码错误");

    // 3.返回token
    const token = jwt.sign(
      {
        id: user._id,
      },
      app.get("secret")
    );
    res.send({
      success: true,
      data: { token: token, userName: userName },
    });
  });
  app.use("/admin/api", router); // 分发路由

  app.use(async (err, req, res, next) => {
    res.status(err.statusCode || 500).send({
      success: false,
      message: err.message,
    });
  }); // 统一错误处理
};
